import { ValidationOptions } from 'sequelize/types/lib/instance-validator';
import { Model, DataTypes, Optional } from 'sequelize';
import sequelize from './index';
import crypto from 'crypto';
import Doudizhu from './doudizhu';

function hashPassword(user: User, options: ValidationOptions): void {
  if (user.changed('password')) {
    user.password = crypto.createHash('md5').update(user.password, 'utf-8').digest('hex');
  }
}

export interface UserAttributes {
  id: number;
  username: string;
  password: string;
  nickname: string;
}

interface UserCreationAttributes extends Optional<UserAttributes, 'id'> { }

class User extends Model<UserAttributes, UserCreationAttributes>
  implements UserAttributes {
  public id!: number;
  public username!: string;
  public password!: string;
  public nickname!: string;

  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
  public readonly deletedAt!: Date;

  public Doudizhu!: any;

  public comparePassword(password: string) {
    return this.password === crypto.createHash('md5').update(password, 'utf-8').digest('hex');
  }
}

User.init(
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      allowNull: false,
      autoIncrement: true,
      comment: '用户Id'
    },
    username: {
      type: DataTypes.STRING(128),
      allowNull: false,
      unique: true,
      validate: {
        len: [4, 128]
      },
      comment: '账号'
    },
    password: {
      type: DataTypes.STRING(128),
      allowNull: false,
      validate: {
        len: [4, 128]
      },
      comment: '密码'
    },
    nickname: {
      type: DataTypes.STRING(16),
      allowNull: false,
      defaultValue: '新用户',
      comment: '昵称'
    }
  },
  {
    hooks: {
      afterValidate: hashPassword
    },
    sequelize,
    modelName: 'User',
    tableName: 'user',
    timestamps: true, // 启用时间戳
    indexes: [{ unique: false, name: 'nickname', fields: ['nickname'] }],
    comment: '用户表'
  }
)

User.hasOne(Doudizhu, { foreignKey: 'uid' });
Doudizhu.belongsTo(User, { foreignKey: 'uid' });

export default User
